package lib

import (
	"fmt"
	"net"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/krio/grpc-common/conf"
	"gitee.com/krio/helper/logger"
	"google.golang.org/grpc"
)

func GRPCServer(server *grpc.Server) error {
	port := conf.C.GRPC.Port
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		return err
	}

	// 协程启动
	go func() {
		if err := server.Serve(lis); err != nil {
			logger.Panicf("start server failed, err:", err)
		}
	}()

	// 自动优雅停止
	c := make(chan os.Signal, 1) // 创建监听退出chan
	// 监听指定信号 ctrl+c kill
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		s := <-c
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			server.GracefulStop()
			return nil
		}
	}
}
